//
//  SAPasswordVC.m
//  saasRetail
//
//  Created by 黄志刚 on 2021/1/26.
//

#import "SAPasswordVC.h"
#import "SAGetCheckCodeView.h"
#import "SAMerchantSendCodeAPI.h"
#import "SAGetPasswordAPI.h"
#import "NSString+MD5.h"

@interface SAPasswordVC ()<HTTPAPIDelegate,UITextFieldDelegate>

@property (nonatomic, strong) UIButton *backBtn;
@property (nonatomic, strong) UITextField *iphoneTf;
@property (nonatomic, strong) UIView *line1;
@property (nonatomic, strong) UITextField *verificationTf;
@property (nonatomic, strong) UIView *line2;
@property (nonatomic, strong) UITextField *passWordTf;
@property (nonatomic, strong) UIView *line3;
@property (nonatomic, strong) UITextField *againPassWordTf;
@property (nonatomic, strong) UIView *line4;
@property (nonatomic, strong) UIButton *completeBtn;

@property (nonatomic, strong) UIButton *validationBtn;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) int count;
@property (nonatomic, strong) SAMerchantSendCodeAPI *merchantSendCodeAPI;
@property (nonatomic, strong) SAGetPasswordAPI *getPasswordAPI;

@end

@implementation SAPasswordVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
}

#pragma mark - HTTPAPIDelegate
- (void)fetchData:(id)data fromServerSuccessedWithAPI:(HTTPAPI *)api {
    if (self.merchantSendCodeAPI == api) {
        [Prompt popPromptViewWithMsg:@"验证码已经发送" duration:2];
        [self startTime];
    }else if (self.getPasswordAPI == api) {
        [Prompt popPromptViewWithMsg:@"找回密码成功!" duration:2];
        [self clickedCloseBtn];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)fetchDataFromServerFailedWithError:(NSError *)error API:(HTTPAPI *)api {
    
}

#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (string.length == 0) {
        return YES;
    }
    if (textField.text.length > 19){
        return NO;
    }
    return YES;
}

#pragma mark - event
-(void)clickedCloseBtn {
    [self dismissViewControllerAnimated:YES completion:nil];
}


-(void)obtainCodeTapEvent {
    [self.view endEditing:YES];
    if(trimString(self.iphoneTf.text).length == 0){
        [Prompt popPromptViewWithMsg:@"请输入手机号码" duration:2];
        return;
    }
    if(trimString(self.iphoneTf.text).length!=11){
        [Prompt popPromptViewWithMsg:@"手机号格式有误，请重新输入" duration:2];
        return;
    }
    
    WeakSelf
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    dict[@"mobile"] =  trimString(weakSelf.iphoneTf.text);
    NSString *url = [NSString stringWithFormat:@"%@:%@/merchant/sendVerify",self.getPasswordAPI.serverAddr,self.getPasswordAPI.serverPort];
    [SANetManager requestWithType:SkyHttpRequestTypeGet urlString:url parameters:dict successBlock:^(id responseObject) {
        [Prompt popPromptViewWithMsg:@"验证码已经发送!" duration:2];
        [weakSelf startTime];
    } failureBlock:^(NSString *error) {
    }];
    
//    开启图形验证码
//    SAGetCheckCodeView *screenView = [SAGetCheckCodeView shareCornView];
//    [screenView loadStr:trimString(self.iphoneTf.text)];
//    [screenView showView:self];
//
//    WeakSelf
//    screenView.selectedCodeBlock = ^(NSDictionary * _Nonnull dic) {
//
//        if(trimString(weakSelf.iphoneTf.text).length == 0){
//            [Prompt popPromptViewWithMsg:@"请输入手机号码" duration:2];
//               return;
//           }
//           if(trimString(weakSelf.iphoneTf.text).length!=11){
//               [Prompt popPromptViewWithMsg:@"手机号格式有误，请重新输入" duration:2];
//               return;
//           }
//        NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
//        dict[@"mobile"] =  trimString(weakSelf.iphoneTf.text);
//        dict[@"sessionId"] = dic[@"sessionId"];
//        dict[@"sig"] = dic[@"sig"];
//        dict[@"token"] = dic[@"token"];
//        dict[@"scene"] = dic[@"scene"];
//        NSString *url = [NSString stringWithFormat:@"%@:%@/merchant/sendCodeManMachineVerify",self.getPasswordAPI.serverAddr,self.getPasswordAPI.serverPort];
//        [SANetManager requestWithType:SkyHttpRequestTypeGet urlString:url parameters:dict successBlock:^(id responseObject) {
//            [Prompt popPromptViewWithMsg:@"验证码已经发送!" duration:2];
//            [weakSelf startTime];
//        } failureBlock:^(NSString *error) {
//        }];
//    };
}


-(void)startTime {
    self.validationBtn.userInteractionEnabled = NO;
    [self.validationBtn setTitle:[NSString stringWithFormat:@"剩余60秒"] forState:UIControlStateNormal];
    self.count = 60;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFired) userInfo:nil repeats:YES];
}

- (void)timerFired {
    if (self.count != 1) {
        self.count -= 1;
        [self.validationBtn setTitle:[NSString stringWithFormat:@"剩余%d秒", self.count] forState:UIControlStateNormal];
    } else {
        self.validationBtn.userInteractionEnabled = YES;
        [self.validationBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        // 停掉定时器
        [self.timer invalidate];
        self.timer = nil;
    }
}

-(void)changeBtnClick
{
    if(trimString(self.iphoneTf.text).length <=0){
        [Prompt popPromptViewWithMsg:@"请输入手机号码!" duration:2];
        return;
    }
    if(trimString(self.iphoneTf.text).length!=11){
        [Prompt popPromptViewWithMsg:@"请输入11位手机号码!" duration:2];
        return;
    }
    if (trimString(self.verificationTf.text).length <=0 || trimString(self.verificationTf.text).length !=6) {
        [Prompt popPromptViewWithMsg:@"请输入正确手机号验证码!" duration:2];
        return;
    }
    if (trimString(self.passWordTf.text).length  <=0) {
        [Prompt popPromptViewWithMsg:@"请输入密码!" duration:2];
        return;
    }
    if(!(trimString(self.passWordTf.text).length >=6 &&trimString(self.passWordTf.text).length <=20)){
        [Prompt popPromptViewWithMsg:@"请输入6-20位数字，字母组合密码 !" duration:2];
        return;
    }
    if (trimString(self.againPassWordTf.text).length <= 0) {
        [Prompt popPromptViewWithMsg:@"请确认密码!" duration:2];
        return;
    }
    if (![trimString(self.againPassWordTf.text) isEqualToString:trimString(self.againPassWordTf.text)]) {
        [Prompt popPromptViewWithMsg:@"两次密码不一致,请重试!" duration:2];
        return;
    }
    
    self.getPasswordAPI.mobile = trimString(self.iphoneTf.text);
    self.getPasswordAPI.checkCode = trimString(self.verificationTf.text);
    self.getPasswordAPI.password = [NSString stringToMD5:trimString(self.againPassWordTf.text)];
    [self.getPasswordAPI sendRequestToServerWithActivityViewAndMask:POST];
}

-(void)buttonClick:(UIButton *)sender {
    sender.selected = !sender.isSelected;
    _passWordTf.secureTextEntry = sender.isSelected;
}

-(void)buttonClick2:(UIButton *)sender {
    sender.selected = !sender.isSelected;
    _againPassWordTf.secureTextEntry = sender.isSelected;
}

#pragma mark - initUI
-(void)initUI {
    self.view.backgroundColor = kLineColor;
    
    UIImageView *topImageV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Login_top"]];
    topImageV.frame = SARectMake(0, 0, kBaseScreenWidth, 165 + DifferenceHeight);
    [self.view addSubview:topImageV];
    
    [self.view addSubview:self.backBtn];
    
    UILabel *tipLab = [[UILabel alloc] initWithFrame:SARectMake(24, 70 + DifferenceHeight, 200, 20)];
    tipLab.text = @"忘记密码";
    tipLab.font = kBFont(18);
    tipLab.textColor = [UIColor whiteColor];
    tipLab.textAlignment = NSTextAlignmentLeft;
    [self.view  addSubview:tipLab];
    
    UIView *whiteView = [[UIView alloc] initWithFrame:SARectMake(15, 128 + DifferenceHeight, 345, 341)];
    whiteView.backgroundColor = [UIColor whiteColor];
    whiteView.layer.cornerRadius = kScaleNum(5);
    whiteView.layer.masksToBounds = YES;
    [self.view addSubview:whiteView];
    
    [whiteView addSubview:self.iphoneTf];
    [whiteView addSubview:self.line1];
    [whiteView addSubview:self.verificationTf];
    [whiteView addSubview:self.line2];
    [whiteView addSubview:self.passWordTf];
    [whiteView addSubview:self.line3];
    [whiteView addSubview:self.againPassWordTf];
    [whiteView addSubview:self.line4];
    [whiteView addSubview:self.completeBtn];
    
    
    UIButton *button = [UIButton buttonWithType:(UIButtonTypeCustom)];
    button.frame = CGRectMake(235, 145, 50, 50);
    [button setImage:[UIImage imageNamed:@"eyeOpen"] forState:(UIControlStateNormal)];
    [button setImage:[UIImage imageNamed:@"eyeClose"] forState:(UIControlStateSelected)];
    [button addTarget:self action:@selector(buttonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    button.selected = YES;
    [whiteView addSubview:button];
    
    UIButton *button2 = [UIButton buttonWithType:(UIButtonTypeCustom)];
    button2.frame = CGRectMake(235, 207, 50, 50);
    [button2 setImage:[UIImage imageNamed:@"eyeOpen"] forState:(UIControlStateNormal)];
    [button2 setImage:[UIImage imageNamed:@"eyeClose"] forState:(UIControlStateSelected)];
    [button2 addTarget:self action:@selector(buttonClick2:) forControlEvents:(UIControlEventTouchUpInside)];
    button2.selected = YES;
    [whiteView addSubview:button2];
   
}

- (UIButton *)backBtn {
    if (!_backBtn) {
        _backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_backBtn setImage:[UIImage imageNamed:@"whiteAllow"] forState:UIControlStateNormal];
        [_backBtn addTarget:self action:@selector(backToLastVC) forControlEvents:UIControlEventTouchUpInside];
        _backBtn.titleLabel.font = kFont(18);
        _backBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        _backBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 15, 0, 0);
        _backBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 15, 0, 0);
        _backBtn.frame = SARectMake(0, StatusHeight - 44, 60, 44);
    }
    return _backBtn;
}

-(UITextField *)iphoneTf {
    if (!_iphoneTf) {
        _iphoneTf = [[UITextField alloc] initWithFrame:SARectMake(60, 38, 225, 16)];
        _iphoneTf.placeholder = @"请输入您的手机号";
        _iphoneTf.font = kFont(14);
        _iphoneTf.textColor = kBlackColor;
    }
    return _iphoneTf;
}

-(UIView *)line1 {
    if (!_line1) {
        _line1 = [[UIView alloc] initWithFrame:SARectMake(60, 62, 225, 1)];
        _line1.backgroundColor = kLineColor;
    }
    return _line1;
}

-(UITextField *)verificationTf {
    if (!_verificationTf) {
        _verificationTf = [[UITextField alloc] initWithFrame:SARectMake(60, 100, 225, 16)];
        _verificationTf.placeholder = @"请输入验证码";
        _verificationTf.font = kFont(14);
        _verificationTf.textColor = kBlackColor;
        UIView *rightView = [[UIView alloc] initWithFrame:SARectMake(0, 0, 89, 35)];
        UIView *line = [[UIView alloc] initWithFrame:SARectMake(0, 10, 1, 17)];
        line.backgroundColor = kBuleColor;
        [rightView addSubview:line];
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = SARectMake(1, 0, 88, 35);
        [btn setTitle:@"获取验证码" forState:UIControlStateNormal];
        btn.titleLabel.font = kFont(14);
        [btn setTitleColor:kBuleColor forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(obtainCodeTapEvent) forControlEvents:UIControlEventTouchUpInside];
        [rightView addSubview:btn];
        self.validationBtn = btn;
        _verificationTf.rightView = rightView;
        _verificationTf.rightViewMode = UITextFieldViewModeAlways;
    }
    return _verificationTf;
}

-(UIView *)line2 {
    if (!_line2) {
        _line2 = [[UIView alloc] initWithFrame:SARectMake(60, 124, 225, 1)];
        _line2.backgroundColor = kLineColor;
    }
    return _line2;
}

-(UITextField *)passWordTf {
    if (!_passWordTf) {
        _passWordTf = [[UITextField alloc] initWithFrame:SARectMake(60, 162, 175, 16)];
        _passWordTf.placeholder = @"输入新密码";
        _passWordTf.font = kFont(14);
        _passWordTf.textColor = kBlackColor;
        _passWordTf.secureTextEntry = YES;
        _passWordTf.delegate = self;
    }
    return _passWordTf;
}

-(UIView *)line3 {
    if (!_line3) {
        _line3 = [[UIView alloc] initWithFrame:SARectMake(60, 186, 225, 1)];
        _line3.backgroundColor = kLineColor;
    }
    return _line3;
}

-(UITextField *)againPassWordTf {
    if (!_againPassWordTf) {
        _againPassWordTf = [[UITextField alloc] initWithFrame:SARectMake(60, 224, 175, 16)];
        _againPassWordTf.placeholder = @"再次输入新密码";
        _againPassWordTf.font = kFont(14);
        _againPassWordTf.textColor = kBlackColor;
        _againPassWordTf.secureTextEntry = YES;
        _againPassWordTf.delegate = self;
    }
    return _againPassWordTf;
}

-(UIView *)line4 {
    if (!_line4) {
        _line4 = [[UIView alloc] initWithFrame:SARectMake(60, 244, 225, 1)];
        _line4.backgroundColor = kLineColor;
    }
    return _line4;
}

-(UIButton *)completeBtn {
    if (!_completeBtn) {
        _completeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _completeBtn.frame = SARectMake(75, 268, 225, 35);
        [_completeBtn setTitle:@"完成" forState:UIControlStateNormal];
        _completeBtn.titleLabel.font = kFont(16);
        [_completeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_completeBtn setBackgroundImage:[UIImage imageNamed:@"Login_btn_1"] forState:UIControlStateNormal];
        [_completeBtn addTarget:self action:@selector(changeBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _completeBtn;
}

-(SAMerchantSendCodeAPI *)merchantSendCodeAPI {
    if (!_merchantSendCodeAPI) {
        _merchantSendCodeAPI = [SAMerchantSendCodeAPI apiWithDelegate:self];
    }
    return _merchantSendCodeAPI;
}

-(SAGetPasswordAPI *)getPasswordAPI {
    if (!_getPasswordAPI) {
        _getPasswordAPI = [SAGetPasswordAPI apiWithDelegate:self];
    }
    return _getPasswordAPI;
}


@end
